package com.xt.xtblesdk6;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;


import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.RequestCallback;
import com.xt.xtblesdk6.ImageFilter.BigBrotherFilter;
import com.xt.xtblesdk6.ImageFilter.BlackWhiteFilter;
import com.xt.xtblesdk6.ImageFilter.BlockPrintFilter;
import com.xt.xtblesdk6.ImageFilter.BrickFilter;
import com.xt.xtblesdk6.ImageFilter.ColorQuantizeFilter;
import com.xt.xtblesdk6.ImageFilter.IImageFilter;
import com.xt.xtblesdk6.ImageFilter.Image;
import com.xt.xtblesdk6.ImageFilter.LUTFilter;
import com.xt.xtblesdk6.ImageFilter.Main.ImageFilterMain;
import com.xt.xtblesdk6.ImageFilter.PosterizeFilter;
import com.xt.xtblesdk6.ImageFilter.SepiaFilter;
import com.xt.xtblesdk6.ImageFilter.ThresholdFilter;
import com.xthh.XTCore;
import com.xthh.XTUI;
import com.xthh._enum.HH_EnumDeviceColorType;
import com.xthh._enum.HH_EnumErrorCode;
import com.xthh._enum.HH_EnumFileType;
import com.xthh._function.HH_CharUtil;
import com.xthh._function.HH_DialogUtil;
import com.xthh._function.HH_FileUtil;
import com.xthh._function.HH_Logging;
import com.xthh._function.HH_PicUtils;
import com.xthh._function.HH_Spinner;
import com.xthh._function.HH_SystemUtil;
import com.xthh._function.HH_TimeUtil;
import com.xthh._function.HH_ToastUtils;
import com.xthh._function._ini.HH_INI;
import com.xthh._msg.HH_MSG;
import com.xthh._struct.HH_T_BindDevice;
import com.xthh._struct.HH_T_DIR_INFO;
import com.xthh._struct.HH_T_RGB_TJ;
import com.xthh._struct.HH_T_SYSTEMTIME;
import com.xthh._struct.HH_T_ScanResult;
import com.xthh._struct.HH_T_SystemParams;
import com.xthh._struct.HH_T_TaskInfo;
import com.xthh.picselect.HH_Activity_PicFileSelect;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;

import butterknife.internal.Utils;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    final String TAG = "MainActivity";
    Context ctx;
    Button button_ota;
    Button button_scan;
    Button button_brushpic;
    Button buttonBrush2;
    Button button_nfc_close;
    Button button_ver_hard;
    Button button_nfc_bind;
    Button button_brushpic_cancel;
    Button button_phone_info;
    Button buttonotp;
    Button button_pic_test;
    Button buttonyltest;
    ImageView imageview_pic;
    TextView textView_w;
    TextView textView_h;
    TextView textView_color;
    TextView textView_mac;
    TextView textView_number;
    TextView textView_dither_point_count;
    TextView textView_color_s;
    TextView textView_sn;
    TextView textView_srrc;
    EditText editText_stop_time;
    EditText editText_battery_yuzi;
    EditText editText_bst;
    TextView textview_bst_16;
    TextView textView_dither_type;
    TextView textView_compress_type;
    TextView textView_compress_pic;
    TextView textView_border_width;
    TextView textView_border_color;
    TextView textView_zoom_type;
    TextView textView_filter_type;
    int dithertype = 0;
    int compresstype = 0;
    int compresspic = 1;
    int borderwidth = 0;
    int bordercolor = 0;
    int zoomtype = 0;
    int filtertype = 0;


    NFCStateReceiver nfcStateReceiver;
    ScreenStatusReceiver mScreenStatusReceiver;
    BluetoothStateReceiver bluetoothStateReceiver;
    ProgressBar progressba_brushpic;

    // 身份认证信息不能更改
    final String strDeviceIdentity = "0000000000";
    final int NFC_BIND_STATE = 102;
    final int MSG_RE_BIND = 701;
    final int MSG_OTHER_LOG = 702;

    String testMac = "A79260A24E1C";
    String strSelectPicPath = "";

    //xiaomi 15 pro      时，   电量<70为0x22,       >=70时为0x1F
    //xiaomi 15s pro     时，   电量<30为0x22,       >=30时为0x1F
   int  epdParams = -1; // EPD驱动参数，1字节，（-1时自动设置，-2保持不变，其它手动设置）

    List<String> list_dither_type = new ArrayList<>();
    List<String> list_compress_type = new ArrayList<>();
    List<String> list_compress_pic = new ArrayList<>();
    List<String> list_border_width = new ArrayList<>();
    List<String> list_border_color = new ArrayList<>();
    List<String> list_zoom_type = new ArrayList<>();
    List<String> list_filter_type = new ArrayList<>();


    public static HandlenRecvMessage handlenRecvMessage;

    boolean bTaskRunning = false;


    int deviceW = 800;
    int deviceH = 480;
    int deviceNumber = 113;
    HH_EnumDeviceColorType deviceColorType = HH_EnumDeviceColorType.BLACK_WHITE_RED_YELLOW_3;
    List<Integer> listSendData = new ArrayList<>();

    private AdapterCurrentTaskLogInfo mAdapterCurrentTaskLogInfo;
    ListView list_log_info;

    // 扩散点数
    int nPointCount = 7;
    List<String> mListPointCount = new ArrayList<>();

    HH_T_SystemParams systemParams;

    String strTJLogInfoPath = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ctx = this;

        //更改标题文字
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle(String.format("SDK_%d_%d", BuildConfig.VERSION_CODE, XTCore.GetLibVer()));

        progressba_brushpic = findViewById(R.id.progressba_brushpic);

        imageview_pic = findViewById(R.id.imageview_pic);
        imageview_pic.setOnClickListener(this);
        button_pic_test = findViewById(R.id.button_pic_test);
        button_pic_test.setOnClickListener(this);

        button_brushpic = findViewById(R.id.button_brushpic);
        button_brushpic.setOnClickListener(this);

        buttonBrush2 = findViewById(R.id.buttonBrush2);
        buttonBrush2.setOnClickListener(this);

        buttonyltest = findViewById(R.id.buttonyltest);
        buttonyltest.setOnClickListener(this);

        button_ota = findViewById(R.id.button_ota);
        button_ota.setOnClickListener(this);
        buttonotp = findViewById(R.id.buttonotp);
        buttonotp.setOnClickListener(this);
        button_nfc_bind = findViewById(R.id.button_nfc_bind);
        button_nfc_bind.setOnClickListener(this);

        button_brushpic_cancel = findViewById(R.id.button_brushpic_cancel);
        button_brushpic_cancel.setOnClickListener(this);
        button_phone_info = findViewById(R.id.button_phone_info);
        button_phone_info.setOnClickListener(this);

        button_ver_hard = findViewById(R.id.button_ver_hard);
        button_ver_hard.setOnClickListener(this);

        button_nfc_close = findViewById(R.id.button_nfc_close);
        button_nfc_close.setOnClickListener(this);

        textView_w = findViewById(R.id.textView_w);
        textView_h = findViewById(R.id.textView_h);
        textView_color = findViewById(R.id.textView_color);
        textView_mac = findViewById(R.id.textView_mac);
        textView_number = findViewById(R.id.textView_number);

        button_scan = findViewById(R.id.button_scan);
        button_scan.setOnClickListener(this);
        textView_dither_type = findViewById(R.id.textView_dither_type);
        textView_dither_type.setOnClickListener(this);
        textView_compress_type = findViewById(R.id.textView_compress_type);
        textView_compress_type.setOnClickListener(this);
        textView_compress_pic = findViewById(R.id.textView_compress_pic);
        textView_compress_pic.setOnClickListener(this);
        textView_border_width = findViewById(R.id.textView_border_width);
        textView_border_width.setOnClickListener(this);
        textView_border_color = findViewById(R.id.textView_border_color);
        textView_border_color.setOnClickListener(this);
        textView_zoom_type = findViewById(R.id.textView_zoom_type);
        textView_zoom_type.setOnClickListener(this);
        textView_filter_type = findViewById(R.id.textView_filter_type);
        textView_filter_type.setOnClickListener(this);
        textView_dither_point_count = findViewById(R.id.textView_dither_point_count);
        textView_dither_point_count.setOnClickListener(this);

        //HH_Logging.i(TAG, "版本号：%d", lib_ver);

        textView_color_s = findViewById(R.id.textView_color_s);
        textView_sn = findViewById(R.id.textView_sn);
        textView_srrc = findViewById(R.id.textView_srrc);


        handlenRecvMessage = new HandlenRecvMessage();

        systemParams = new HH_T_SystemParams(getApplication(), ctx, handlenRecvMessage);


        list_log_info = findViewById(R.id.list_log_info);
        mAdapterCurrentTaskLogInfo = new AdapterCurrentTaskLogInfo(this);
        list_log_info.setAdapter(mAdapterCurrentTaskLogInfo);
        AddLogInfo(String.format("lib版本号=%d", XTCore.GetLibVer()));

        deviceW = HH_INI.getInt(systemParams, "DEVICE_W");
        deviceH = HH_INI.getInt(systemParams, "DEVICE_H");
        deviceNumber = HH_INI.getInt(systemParams, "DEVICE_NUMBER");
        testMac = HH_INI.getString(systemParams, "DEVICE_MAC");


        String packageName = ctx.getPackageName();
        packageName = packageName.replaceAll("\\.", "_");
        String rootDataDir = Environment.getExternalStorageDirectory().getPath();
        rootDataDir = rootDataDir + File.separator + "." + packageName + File.separator;
        HH_FileUtil.CreateFolder(rootDataDir);
        strTJLogInfoPath = rootDataDir + "tj.txt";



        deviceColorType = HH_INI.getDeviceColor(systemParams, "DEVICE_COLOR");
        if (deviceW == 0 || deviceH == 0){
            deviceW = 528;
            deviceH = 768;
            testMac = "A79260A24E1C";
            deviceNumber = 113;
            deviceColorType = HH_EnumDeviceColorType.BLACK_WHITE_RED_YELLOW_3;

            HH_INI.putInt(systemParams, "DEVICE_W", deviceW);
            HH_INI.putInt(systemParams, "DEVICE_H", deviceH);
            HH_INI.putInt(systemParams, "DEVICE_NUMBER", deviceNumber);
            HH_INI.putString(systemParams, "DEVICE_MAC", testMac);
            HH_INI.putDeviceColor(systemParams, "DEVICE_COLOR", deviceColorType);
        }

        //HH_INI.putString(systemParams, "DEVICE_MAC", "A79260A24E1C");
        /*deviceW = 400;
        deviceH = 400;
        deviceColorType = HH_EnumDeviceColorType.E6_5;*/

        list_dither_type = new ArrayList<>();
        list_dither_type.add("色阶");
        list_dither_type.add("标准亮度抖点");
        list_dither_type.add("亮度调暗抖点");
        list_dither_type.add("亮度调亮抖点");

        dithertype = HH_INI.getInt(systemParams, "dithertypext");
        if (dithertype >= 0 && dithertype < list_dither_type.size()){
            for (int i = 0; i < list_dither_type.size(); i++){
                if (dithertype == i){
                    textView_dither_type.setText(list_dither_type.get(i));
                }
            }
        } else {
            dithertype = 0;
            HH_INI.putInt(systemParams, "dithertypext", dithertype);
        }


        list_compress_type = new ArrayList<>();
        list_compress_type.add("数据自动压缩");
        list_compress_type.add("数据压缩");
        list_compress_type.add("数据不压缩");
        compresstype = HH_INI.getInt(systemParams, "compresstype");
        if (compresstype >= 0 && compresstype < list_compress_type.size()){
            for (int i = 0; i < list_compress_type.size(); i++){
                if (compresstype == i){
                    textView_compress_type.setText(list_compress_type.get(i));
                }
            }
        } else {
            compresstype = 0;
            HH_INI.putInt(systemParams, "compresstype", compresstype);
        }

        list_compress_pic = new ArrayList<>();
        for (int i = 1; i <= 100; i++)
            list_compress_pic.add(String.format("压缩比-%d", i));
        compresspic = HH_INI.getInt(systemParams, "compresspic");
        if (compresspic >= 0 && compresspic < list_compress_pic.size()){
            for (int i = 0; i < list_compress_pic.size(); i++){
                if (compresspic == i){
                    textView_compress_pic.setText(list_compress_pic.get(i));
                }
            }
        } else {
            compresspic = 0;
            HH_INI.putInt(systemParams, "compresspic", compresspic);
        }



        ///////////////////////
        list_border_width = new ArrayList<>();
        for (int i = 0; i < 250; i++)
            list_border_width.add(String.format("边界宽-%d", i));
        borderwidth = HH_INI.getInt(systemParams, "borderwidth");
        if (borderwidth >= 0 && borderwidth < list_border_width.size()){
            for (int i = 0; i < list_border_width.size(); i++){
                if (borderwidth == i){
                    textView_border_width.setText(list_border_width.get(i));
                }
            }
        } else {
            borderwidth = 0;
            HH_INI.putInt(systemParams, "borderwidth", borderwidth);
        }
        /////////////////////////////

        ///////////////////////
        list_border_color = new ArrayList<>();
        list_border_color.add("边界色-黑");
        list_border_color.add("边界色-白");
        list_border_color.add("边界色-红");
        list_border_color.add("边界色-黄");
        bordercolor = HH_INI.getInt(systemParams, "bordercolor");
        if (bordercolor >= 0 && bordercolor < list_border_color.size()){
            for (int i = 0; i < list_border_color.size(); i++){
                if (bordercolor == i){
                    textView_border_color.setText(list_border_color.get(i));
                }
            }
        } else {
            bordercolor = 0;
            HH_INI.putInt(systemParams, "bordercolor", bordercolor);
        }
        /////////////////////////////

        ///////////////////////
        list_zoom_type = new ArrayList<>();
        list_zoom_type.add("位伸");
        list_zoom_type.add("等比例缩放");
        zoomtype = HH_INI.getInt(systemParams, "zoomtype");
        if (zoomtype >= 0 && zoomtype < list_zoom_type.size()){
            for (int i = 0; i < list_zoom_type.size(); i++){
                if (zoomtype == i){
                    textView_zoom_type.setText(list_zoom_type.get(i));
                }
            }
        } else {
            zoomtype = 0;
            HH_INI.putInt(systemParams, "zoomtype", zoomtype);
        }
        /////////////////////////////

        ///////////////////////
        list_filter_type = new ArrayList<>();
        list_filter_type.add("滤镜-无");
        list_filter_type.add("滤镜-1");
        list_filter_type.add("滤镜-2");
        list_filter_type.add("滤镜-3");
        list_filter_type.add("滤镜-4");
        list_filter_type.add("滤镜-5");
        list_filter_type.add("滤镜-6");
        list_filter_type.add("滤镜-7");
        list_filter_type.add("滤镜-8");
        filtertype = HH_INI.getInt(systemParams, "filtertype");
        if (filtertype >= 0 && filtertype < list_filter_type.size()){
            for (int i = 0; i < list_filter_type.size(); i++){
                if (filtertype == i){
                    textView_filter_type.setText(list_filter_type.get(i));
                }
            }
        } else {
            filtertype = 0;
            HH_INI.putInt(systemParams, "filtertype", filtertype);
        }
        /////////////////////////////


        mListPointCount = new ArrayList<>();
        for (int i = 0; i < 8; i++){
            mListPointCount.add(String.format("%d", i));
        }
        nPointCount = HH_INI.getInt(systemParams, "nPointCount");

        if (nPointCount < 2)
            nPointCount = 2;
        else if (nPointCount > 7)
            nPointCount = 7;
        HH_INI.putInt(systemParams, "nPointCount", nPointCount);
        for (int i = 0; i < mListPointCount.size(); i++){
            if (nPointCount == i){
                textView_dither_point_count.setText(mListPointCount.get(i));
            }
        }





        //HH_INI.putString(systemParams, "DEVICE_MAC", "38360F017DD4");

        // 测试，强度改为16色
        //deviceColorType = HH_EnumDeviceColorType.N_COLOR_16_6;

        textView_w.setText(String.format("%d", deviceW));
        textView_h.setText(String.format("%d", deviceH));
        textView_number.setText(String.format("%d", deviceNumber));
        textView_mac.setText(testMac);
        textView_color.setText(String.format("%d", deviceColorType.ordinal()));

        SetStopTime();
        SetBatteryYz();
        SetBST();

        if (nfcStateReceiver == null) {
            nfcStateReceiver = new NFCStateReceiver();
        }
        IntentFilter filter = new IntentFilter();
        IntentFilter nfcFilter = new IntentFilter();
        filter.addAction(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
        registerReceiver(nfcStateReceiver, filter);


        if (mScreenStatusReceiver == null){
            mScreenStatusReceiver = new ScreenStatusReceiver();
        }
        IntentFilter screenStatusIF = new IntentFilter();
        screenStatusIF.addAction(Intent.ACTION_SCREEN_ON);
        screenStatusIF.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mScreenStatusReceiver, screenStatusIF);


        if (bluetoothStateReceiver == null) {
            bluetoothStateReceiver = new BluetoothStateReceiver();
        }
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(bluetoothStateReceiver, filter);



        OpenPerm();
    }

    private void SetBST() {
        textview_bst_16 = findViewById(R.id.textview_bst_16);
        editText_bst = findViewById(R.id.editText_bst);
        editText_bst.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s != null && s.toString() != null){
                    int time = HH_CharUtil.Atoi(s.toString());
                    if (time > 0){
                        HH_INI.putInt(systemParams, "editText_bst", time);
                        textview_bst_16.setText(String.format("0x%02X", time));
                    }
                }
            }
        });

        int time = HH_INI.getInt(systemParams, "editText_bst");
        if (time <= 0){
            time = 1;
            HH_INI.putInt(systemParams, "editText_bst", time);
        }
        editText_bst.setText(String.format("%d", time));
    }

    private void SetBatteryYz() {

        editText_battery_yuzi = findViewById(R.id.editText_battery_yuzi);
        editText_battery_yuzi.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s != null && s.toString() != null){
                    int time = HH_CharUtil.Atoi(s.toString());
                    if (time > 0)
                        HH_INI.putInt(systemParams, "editText_battery_yuzi", time);
                }
            }
        });

        int time = HH_INI.getInt(systemParams, "editText_battery_yuzi");
        if (time <= 0){
            time = 1;
            HH_INI.putInt(systemParams, "editText_battery_yuzi", time);
        }
        editText_battery_yuzi.setText(String.format("%d", time));

    }

    private void SetStopTime() {
        editText_stop_time = findViewById(R.id.editText_stop_time);
        editText_stop_time.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s != null && s.toString() != null){
                    int time = HH_CharUtil.Atoi(s.toString());
                    if (time > 0)
                        HH_INI.putInt(systemParams, "STOP_TIME_13", time);
                }
            }
        });

        int time = HH_INI.getInt(systemParams, "STOP_TIME_13");
        if (time <= 0){
            time = 1;
            HH_INI.putInt(systemParams, "STOP_TIME_13", time);
        }
        editText_stop_time.setText(String.format("%d", time));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(nfcStateReceiver);
        unregisterReceiver(mScreenStatusReceiver);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }



    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    private void OpenPerm() {
        PermissionX.init(this)
                .permissions(
                        Manifest.permission.BLUETOOTH,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        //Manifest.permission.MANAGE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .explainReasonBeforeRequest()
                .onExplainRequestReason((scope, deniedList, beforeRequest) -> scope.showRequestReasonDialog(deniedList,
                        "即将申请的权限是程序必须的权限",
                        "确定",
                        "取消"))
                .request(new RequestCallback() {
                    @Override
                    public void onResult(boolean allGranted, @NonNull List<String> grantedList, @NonNull List<String> deniedList) {
                        if (allGranted) {
                            initApp();
                        } else {
                            //requestPermission();
                        }
                    }
                });
    }

    private void initApp() {
    }

    /*public Bitmap cartoonEffect(Bitmap input) {
        Mat src = new Mat();
        Utils.bitmapToMat(input, src);

        // 1. 边缘检测
        Mat edges = new Mat();
        Imgproc.cvtColor(src, src, Imgproc.COLOR_RGBA2RGB);
        Imgproc.adaptiveThreshold(
                getGrayScale(src), edges, 255,
                Imgproc.ADAPTIVE_THRESH_MEAN_C,
                Imgproc.THRESH_BINARY, 9, 2
        );

        // 2. 色彩简化
        Mat reduced = new Mat();
        Imgproc.bilateralFilter(src, reduced, 9, 150, 150);

        // 3. 合并结果
        Mat cartoon = new Mat();
        Core.bitwise_and(reduced, reduced, cartoon, edges);

        Bitmap output = Bitmap.createBitmap(cartoon.cols(), cartoon.rows(), Bitmap.Config.ARGB_8888);
        Utils.matToBitmap(cartoon, output);
        return output;
    }*/


    private void LoadLocalPic(String src) {
        Bitmap bSrc = HH_PicUtils.GetBitmapFormFile(src);
        if (bSrc != null) {
            if (bSrc.getWidth() != deviceW || bSrc.getHeight() != deviceH) {

                if (zoomtype == 0){
                    bSrc = HH_PicUtils.scaleBitmap(bSrc, deviceW, deviceH);
                } else {
                    bSrc = HH_PicUtils.zoomImg2(bSrc, deviceW, deviceH, 0, 0, 0);
                }
            }


            if (bSrc != null) {
                Image img = null;
                img = new Image(bSrc);

                switch (filtertype){
                    case 0:{
                        break;
                    }
                    case 1:{
                      
                        IImageFilter filter = new BlackWhiteFilter();
                        if (filter != null) {
                            img = filter.process(img);
                            img.copyPixelsFromBuffer();
                        }
                        break;
                    }
                    case 2:{
                      
                        IImageFilter filter = new BigBrotherFilter();
                        if (filter != null) {
                            img = filter.process(img);
                            img.copyPixelsFromBuffer();
                        }
                        break;
                    }
                    case 3:{
                      
                        IImageFilter filter = new ThresholdFilter();
                        if (filter != null) {
                            img = filter.process(img);
                            img.copyPixelsFromBuffer();
                        }
                        break;
                    }
                    case 4:{
                      
                        IImageFilter filter = new BlockPrintFilter();
                        if (filter != null) {
                            img = filter.process(img);
                            img.copyPixelsFromBuffer();
                        }
                        break;
                    }
                    case 5:{
                      
                        IImageFilter filter = new BrickFilter();
                        if (filter != null) {
                            img = filter.process(img);
                            img.copyPixelsFromBuffer();
                        }
                        break;
                    }
                    case 6:{
                      
                        IImageFilter filter = new ColorQuantizeFilter();
                        if (filter != null) {
                            img = filter.process(img);
                            img.copyPixelsFromBuffer();
                        }
                        break;
                    }
                    case 7:{

                        IImageFilter filter = new PosterizeFilter(2);
                        if (filter != null) {
                            img = filter.process(img);
                            img.copyPixelsFromBuffer();
                        }
                        break;
                    }
                    default:{
                      
                        IImageFilter filter = new SepiaFilter();
                        if (filter != null) {
                            img = filter.process(img);
                            img.copyPixelsFromBuffer();
                        }
                        break;
                    }

                }


                // 测试的图需要旋转
                bSrc = HH_PicUtils.rotateBitmap(filtertype == 0 ? bSrc : img.getImage(), 270);
                Long timeBegin = HH_TimeUtil.MadeMillisTimeMS();

                if (compresspic > 95){

                } else {
                    // 压缩
                    String tempPath3 = YS(bSrc, compresspic, 15);
                    bSrc = HH_PicUtils.GetBitmapFormFile(tempPath3);
                }


                if (borderwidth <= 0){
                    // 不加边框了
                } else {
                    // 修改边界的宽和颜色
                    switch (bordercolor){
                        case 0:
                            bSrc = ChangeBorderInfo(bSrc, 0, 0, 0, borderwidth);
                            break;
                        case 1:
                            bSrc = ChangeBorderInfo(bSrc, 255, 255, 255, borderwidth);
                            break;
                        case 2:
                            bSrc = ChangeBorderInfo(bSrc, 255, 0, 0, borderwidth);
                            break;
                        default:
                            bSrc = ChangeBorderInfo(bSrc, 255, 255, 0, borderwidth);
                    }

                }



                // 新增抖点
                bSrc = XTCore.PicDither(bSrc, deviceColorType, dithertype != 0, dithertype);

                HH_Logging.i(TAG, "抖点耗时：%d,分辨率=%d*%d", HH_TimeUtil.MadeMillisTimeMS() - timeBegin, bSrc.getWidth(), bSrc.getHeight());

                if (bSrc != null) {
                    listSendData = new ArrayList<>();

                    switch (compresstype){
                        case 0:{
                            listSendData = XTCore.GetSendPicData(bSrc, deviceColorType);
                            break;
                        }
                        case 1:{
                            listSendData = XTCore.GetSendPicData(bSrc, deviceColorType, true);
                            break;
                        }
                        default:{
                            listSendData = XTCore.GetSendPicData(bSrc, deviceColorType, false);
                        }
                    }

                    HH_Logging.i(TAG, "%d", listSendData.size());

                    // 临时写入文件
                    String tempPath = HH_SystemUtil.GetTempPath(systemParams, 0, HH_EnumFileType.BMP);
                    HH_PicUtils.BitmapSaveFile(bSrc, tempPath);
                    Bitmap b2 = HH_PicUtils.GetBitmapFormFile(tempPath);
                    b2 = HH_PicUtils.rotateBitmap(b2, 90);

                    List<HH_T_RGB_TJ> colorInfo2 = XTCore.GetPicColorTypeCount(b2);
                    if (colorInfo2 != null){
                        HH_Logging.i(TAG, "颜色个数=%d,颜色=%s", colorInfo2.size(), deviceColorType.toString());
                        for (int i = 0; i < colorInfo2.size(); i++){
                            HH_Logging.i(TAG, "RGB=%d,%d,%d", colorInfo2.get(i).getR(), colorInfo2.get(i).getG(), colorInfo2.get(i).getB(), colorInfo2.get(i).getCount());
                        }
                    }

                    imageview_pic.setImageBitmap(b2);
                }
            }
        }
    }

    private Bitmap ChangeBorderInfo(Bitmap srcBitmp, int borderR, int borderG, int borderB, int bw) {


        int cols = srcBitmp.getWidth();
        int rows = srcBitmp.getHeight();


        Bitmap backgroundBmp = Bitmap.createBitmap(srcBitmp.getWidth(), srcBitmp.getHeight(), Bitmap.Config.ARGB_8888);

        HH_Logging.i(TAG, "ChangeLineColor, %d,%d", rows, cols);
        int index = 0;
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (col < bw || row < bw || col > cols-bw || row > rows-bw){
                    backgroundBmp.setPixel(col, row, Color.rgb(borderR, borderG, borderB));
                }
                else{
                    int pixel = srcBitmp.getPixel(col, row);
                    int r = Color.red(pixel);
                    int g = Color.green(pixel);
                    int b = Color.blue(pixel);
                    backgroundBmp.setPixel(col, row, Color.rgb(r, g, b));
                }
            }
        }
        return backgroundBmp;
    }


    private String YS(Bitmap b1, int compressValue, int fileIndex) {
        final CountDownLatch latch1 = new CountDownLatch(1);
        HH_Logging.i(TAG, "com begin");
        String tempPath1 = HH_SystemUtil.GetTempPath(systemParams,fileIndex, HH_EnumFileType.JPG);
        HH_PicUtils.CompressImageByQuality(b1, tempPath1, compressValue, new HH_PicUtils.ResultCallBackWrite() {
            @Override
            public void callback(String writeResult) {
                HH_Logging.i(TAG, "com callback path = %s", writeResult);

                latch1.countDown();
            }
        });


        try {
            latch1.await();
        } catch (InterruptedException e) {
        }

        return tempPath1;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.buttonyltest:{
                // 批量测试
                if (bTaskRunning){
                    HH_DialogUtil.tipsDialog(ctx, "任务正在运行");
                    break;
                }
                new Thread(new Runnable() {
                    public void run() {
                        bTaskRunning = true;
                        try {

                            if (listSendData != null && listSendData.size() > 0){
                                int time = 1;
                                if (editText_stop_time.getText() == null || editText_stop_time.getText().toString() == null){
                                    time = 1;
                                } else {
                                    time = HH_CharUtil.Atoi(editText_stop_time.getText().toString());
                                }
                                HH_Logging.i(TAG, "超时间=%d", time);

                                int bst = 1;
                                if (editText_bst.getText() == null || editText_bst.getText().toString() == null){
                                    bst = 1;
                                } else {
                                    bst = HH_CharUtil.Atoi(editText_bst.getText().toString());
                                }
                                bst = bst & 0xFF;

                                final int test_count = 5;
                                int nFailCount = 0;
                                for (int testIndex = 0; testIndex < test_count; testIndex++){
                                    long timeBegin = HH_TimeUtil.MadeMillisTimeMS();
                                    HH_EnumErrorCode code =  XTCore.BrushPic(systemParams, testMac, listSendData, 10, true, strDeviceIdentity, 1, bst);

                                    if (code != HH_EnumErrorCode.SUCCESS){
                                        nFailCount++;
                                    }


                                    /*String writeInfo = String.format("\n***********************\nMAC=%s,\n结果=%s,\n耗时=%d毫秒，\n手机型号=%s,\n电量=%d,\nBST=%s,\nPIC=%s,\n抖点类型=%s,\n%s,\n%s,\n%s,\n%s,\n刷图前等待时间=%s毫秒",
                                            testMac,
                                            code.toString(),
                                            HH_TimeUtil.MadeMillisTimeMS() - timeBegin,
                                            HH_SystemUtil.getDeviceModel(),
                                            HH_SystemUtil.GetBatteryPercentage(ctx),
                                            textview_bst_16.getText().toString(),
                                            strSelectPicPath,
                                            textView_dither_type.getText().toString(),
                                            textView_compress_pic.getText().toString(),
                                            textView_border_width.getText().toString(),
                                            textView_border_color.getText().toString(),
                                            textView_filter_type.getText().toString(),
                                            editText_stop_time.getText().toString());*/

                                    HH_T_DIR_INFO dirInfo = HH_FileUtil.GetCurFileInfo(strSelectPicPath);

                                    String writeInfo = String.format("刷图统计===>   MAC=%s,结果=%s,电量=%d,%s,文件名=%s\n",
                                            testMac,
                                            code.toString(),
                                            HH_SystemUtil.GetBatteryPercentage(ctx),
                                            textView_filter_type.getText().toString(),
                                            dirInfo.getNameF());
                                    //SendToDD(writeInfo);
                                    //11
                                    HH_FileUtil.WriteFile(strTJLogInfoPath, writeInfo, true);
                                    HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, writeInfo, 0, 0);

                                    if (testIndex < test_count - 1){
                                        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                                        HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, "等待20秒", 0, 0);
                                        HH_SystemUtil.Sleep(1000 * 20);
                                        vibrator.vibrate(2000);
                                    }
                                }

                                HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, String.format("测试完成，共失败%d次", nFailCount), 0, 0);
                            }

                        } catch (Exception e) {
                            HH_Logging.i(TAG, "brush-end fail = %s", e.toString());
                            e.printStackTrace();
                        }
                        bTaskRunning = false;
                    }
                }).start();
                break;
            }
            case R.id.button_pic_test:{
                Intent intent = new Intent(this, ImageFilterMain.class);
                startActivity(intent);
                break;
            }
            case R.id.buttonotp:{
                if (bTaskRunning){
                    HH_DialogUtil.tipsDialog(ctx, "任务正在运行");
                    break;
                }
                new Thread(new Runnable() {
                    public void run() {
                        bTaskRunning = true;
                        try {
                            HH_EnumErrorCode code = XTCore.LedControl(systemParams, testMac, "", 1, 1, 1);
                            HH_Logging.i(TAG, systemParams, "XTCore.OTP = %s", code.toString());

                            HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, "OTP-" + code.toString(), 0, 0);
                        } catch (Exception e) {
                            HH_Logging.i(TAG, systemParams, "XTCore.OTP-FAIL2");
                            e.printStackTrace();
                        }
                        bTaskRunning = false;
                    }
                }).start();
                break;
            }
            case R.id.textView_dither_point_count:{
                XTUI.Spinner(systemParams, mListPointCount, textView_dither_point_count, textView_dither_point_count.getWidth(), 500, nPointCount, new HH_Spinner.ResultCallBack() {
                    @Override
                    public void callback(int pos, String value) {
                        if (pos < 2){
                            nPointCount = 2;
                        } else {
                            nPointCount = pos;
                        }
                        HH_INI.putInt(systemParams, "nPointCount", nPointCount);
                        textView_dither_point_count.setText(String.format("%d", nPointCount));

                        // 重新加载图片
                        LoadLocalPic(strSelectPicPath);
                    }
                }, new HH_Spinner.ResultDisBack() {
                    @Override
                    public void callback(int pos, String value) {
                        HH_Logging.i(TAG, "ResultDisBack");
                    }
                });
                break;
            }
            case R.id.textView_dither_type:{
                XTUI.Spinner(systemParams, list_dither_type, textView_dither_type, textView_dither_type.getWidth(), 1000, dithertype, new HH_Spinner.ResultCallBack() {
                    @Override
                    public void callback(int pos, String value) {
                        dithertype = pos;
                        HH_INI.putInt(systemParams, "dithertypext", dithertype);

                        for (int i = 0; i < list_dither_type.size(); i++){
                            if (dithertype == i){
                                textView_dither_type.setText(list_dither_type.get(i));
                            }
                        }

                        // 重新加载图片
                        LoadLocalPic(strSelectPicPath);

                        /*Intent intent = new Intent(ctx, HH_Activity_PicFileSelect.class);
                        ArrayList<String> listExts = new ArrayList<String>();
                        listExts.add("png");
                        listExts.add("jpg");
                        listExts.add("jpeg");
                        listExts.add("bmp");
                        intent.putStringArrayListExtra("FIND_FILE_EXT", listExts);
                        startActivityForResult(intent, HH_MSG.XT_FILE_SELECT_PIC);*/
                    }
                }, new HH_Spinner.ResultDisBack() {
                    @Override
                    public void callback(int pos, String value) {
                        HH_Logging.i(TAG, "ResultDisBack");
                    }
                });
                break;
            }

            case R.id.textView_compress_type:{
                XTUI.Spinner(systemParams, list_compress_type, textView_compress_type, textView_compress_type.getWidth(), 1000, compresstype, new HH_Spinner.ResultCallBack() {
                    @Override
                    public void callback(int pos, String value) {
                        compresstype = pos;
                        HH_INI.putInt(systemParams, "compresstype", compresstype);

                        for (int i = 0; i < list_compress_type.size(); i++){
                            if (compresstype == i){
                                textView_compress_type.setText(list_compress_type.get(i));
                            }
                        }
                    }
                }, new HH_Spinner.ResultDisBack() {
                    @Override
                    public void callback(int pos, String value) {
                        HH_Logging.i(TAG, "ResultDisBack");
                    }
                });
                break;
            }

            case R.id.textView_border_width:{
                XTUI.Spinner(systemParams, list_border_width, textView_border_width, textView_border_width.getWidth(), 1000, borderwidth, new HH_Spinner.ResultCallBack() {
                    @Override
                    public void callback(int pos, String value) {
                        borderwidth = pos;
                        HH_INI.putInt(systemParams, "borderwidth", borderwidth);

                        for (int i = 0; i < list_border_width.size(); i++){
                            if (borderwidth == i){
                                textView_border_width.setText(list_border_width.get(i));
                            }
                        }

                        // 重新加载图片
                        LoadLocalPic(strSelectPicPath);
                    }
                }, new HH_Spinner.ResultDisBack() {
                    @Override
                    public void callback(int pos, String value) {
                        HH_Logging.i(TAG, "ResultDisBack");
                    }
                });
                break;
            }

            case R.id.textView_border_color:{
                XTUI.Spinner(systemParams, list_border_color, textView_border_color, textView_border_color.getWidth(), 1000, bordercolor, new HH_Spinner.ResultCallBack() {
                    @Override
                    public void callback(int pos, String value) {
                        bordercolor = pos;
                        HH_INI.putInt(systemParams, "bordercolor", bordercolor);

                        for (int i = 0; i < list_border_color.size(); i++){
                            if (bordercolor == i){
                                textView_border_color.setText(list_border_color.get(i));
                            }
                        }


                        // 重新加载图片
                        LoadLocalPic(strSelectPicPath);
                    }
                }, new HH_Spinner.ResultDisBack() {
                    @Override
                    public void callback(int pos, String value) {
                        HH_Logging.i(TAG, "ResultDisBack");
                    }
                });
                break;
            }

            case R.id.textView_zoom_type:{
                XTUI.Spinner(systemParams, list_zoom_type, textView_zoom_type, textView_zoom_type.getWidth(), 1000, zoomtype, new HH_Spinner.ResultCallBack() {
                    @Override
                    public void callback(int pos, String value) {
                        zoomtype = pos;
                        HH_INI.putInt(systemParams, "zoomtype", zoomtype);

                        for (int i = 0; i < list_zoom_type.size(); i++){
                            if (zoomtype == i){
                                textView_zoom_type.setText(list_zoom_type.get(i));
                            }
                        }


                        // 重新加载图片
                        LoadLocalPic(strSelectPicPath);
                    }
                }, new HH_Spinner.ResultDisBack() {
                    @Override
                    public void callback(int pos, String value) {
                    }
                });
                break;
            }

            case R.id.textView_filter_type:{
                XTUI.Spinner(systemParams, list_filter_type, textView_filter_type, textView_filter_type.getWidth(), 1000, filtertype, new HH_Spinner.ResultCallBack() {
                    @Override
                    public void callback(int pos, String value) {
                        filtertype = pos;
                        HH_INI.putInt(systemParams, "filtertype", filtertype);

                        for (int i = 0; i < list_filter_type.size(); i++){
                            if (filtertype == i){
                                textView_filter_type.setText(list_filter_type.get(i));
                            }
                        }


                        // 重新加载图片
                        LoadLocalPic(strSelectPicPath);
                    }
                }, new HH_Spinner.ResultDisBack() {
                    @Override
                    public void callback(int pos, String value) {
                    }
                });
                break;
            }

            case R.id.textView_compress_pic:{
                XTUI.Spinner(systemParams, list_compress_pic, textView_compress_pic, textView_compress_pic.getWidth(), 1000, compresspic, new HH_Spinner.ResultCallBack() {
                    @Override
                    public void callback(int pos, String value) {
                        compresspic = pos;
                        HH_INI.putInt(systemParams, "compresspic", compresspic);

                        for (int i = 0; i < list_compress_pic.size(); i++){
                            if (compresspic == i){
                                textView_compress_pic.setText(list_compress_pic.get(i));
                            }
                        }


                        // 重新加载图片
                        LoadLocalPic(strSelectPicPath);
                    }
                }, new HH_Spinner.ResultDisBack() {
                    @Override
                    public void callback(int pos, String value) {
                        HH_Logging.i(TAG, "ResultDisBack");
                    }
                });
                break;
            }
            case R.id.button_nfc_bind:{
                Intent intent = new Intent(this, NFCBindActivity2.class);
                startActivityForResult(intent, NFC_BIND_STATE);

                break;
            }
            case R.id.button_ver_hard:{
                if (bTaskRunning){
                    HH_DialogUtil.tipsDialog(ctx, "任务正在运行");
                    break;
                }
                new Thread(new Runnable() {
                    public void run() {
                        bTaskRunning = true;
                        try {
                            HH_Logging.i(TAG, systemParams,"固件版本号：%s", XTCore.GetHardVersion(systemParams, testMac));
                            AddLogInfo(String.format("固件版本号：%s", XTCore.GetHardVersion(systemParams, testMac)));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        bTaskRunning = false;
                    }
                }).start();
                break;
            }
            case R.id.button_scan:{
                if (bTaskRunning){
                    HH_DialogUtil.tipsDialog(ctx, "任务正在运行");
                    break;
                }
                new Thread(new Runnable() {
                    public void run() {
                        bTaskRunning = true;
                        try {
                            HH_Logging.i(TAG, "scan-begin");
                            ArrayList<HH_T_ScanResult> list = XTCore.Scan(systemParams, testMac);
                            if (list != null){
                                for (int i = 0; i < list.size(); i++){
                                    if (list.get(i).getBindDevice() != null){
                                        HH_Logging.i(TAG, "mac=%s,rssi=%d", list.get(i).getBindDevice().getMacRes(), list.get(i).getBindDevice().getDbm());

                                        deviceW = list.get(i).getBindDevice().getWidth();
                                        deviceH = list.get(i).getBindDevice().getHeight();
                                        deviceColorType = list.get(i).getBindDevice().getDeviceColorType();

                                        HH_INI.putInt(systemParams, "DEVICE_W", deviceW);
                                        HH_INI.putInt(systemParams, "DEVICE_H", deviceH);
                                        HH_INI.putString(systemParams, "DEVICE_MAC", list.get(i).getBindDevice().getMacRes());
                                        HH_INI.putDeviceColor(systemParams, "DEVICE_COLOR", deviceColorType);
                                    }
                                }
                            }
                            HH_Logging.i(TAG, "scan-end");

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        bTaskRunning = false;
                    }
                }).start();
                break;
            }
            case R.id.button_brushpic_cancel:{
                if (bTaskRunning){
                    HH_DialogUtil.tipsDialog(ctx, "任务正在运行");
                    break;
                }
                AddLogInfo("主动取消");
                new Thread(new Runnable() {
                    public void run() {
                        bTaskRunning = true;
                        try {
                            HH_EnumErrorCode code = NFCClose(testMac);
                            HH_Logging.i(TAG, systemParams, "XTCore.NFCClose = %s", code.toString());
                            HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, code.toString(), 0, 0);
                            XTCore.StopBrushPic();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        bTaskRunning = false;
                    }
                }).start();
                break;
            }
            case R.id.button_brushpic:{
                if (bTaskRunning){
                    HH_DialogUtil.tipsDialog(ctx, "任务正在运行");
                    break;
                }
                if (listSendData == null || listSendData.size() <= 0){
                    HH_ToastUtils.showToast(ctx, "先选图");
                    break;
                }

                if (deviceNumber != 113){
                    AddLogInfo("设备不匹配");
                    break;
                }

                new Thread(new Runnable() {
                    public void run() {
                        bTaskRunning = true;
                        try {
                            HH_EnumErrorCode code = BrushPic(testMac, listSendData);
                            HH_Logging.i(TAG, systemParams, "XTCore.BrushPic = %s", code.toString());
                            if (code == HH_EnumErrorCode.BLE_CONNECT_FAIL){
                                //HH_SystemUtil.SendMessage(systemParams, MSG_RE_BIND, "", 0, 0);
                            } else if (code == HH_EnumErrorCode.FAIL){
                                HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, "传输失败", 0, 0);
                            } else if (code == HH_EnumErrorCode.BRUSH_FAIL){
                                HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, "刷图失败", 0, 0);
                            }
                        } catch (Exception e) {
                            HH_Logging.i(TAG, "brush-end fail = %s", e.toString());
                            e.printStackTrace();
                        }
                        bTaskRunning = false;
                    }
                }).start();
                break;
            }
            case R.id.buttonBrush2:{
                if (bTaskRunning){
                    HH_DialogUtil.tipsDialog(ctx, "任务正在运行");
                    break;
                }
                if (listSendData == null || listSendData.size() <= 0){
                    HH_ToastUtils.showToast(ctx, "先选图");
                    break;
                }

                if (deviceNumber != 113){
                    AddLogInfo("设备不匹配");
                    break;
                }

                new Thread(new Runnable() {
                    public void run() {
                        bTaskRunning = true;
                        try {

                            if (listSendData != null && listSendData.size() > 0){
                                int time = 1;
                                if (editText_stop_time.getText() == null || editText_stop_time.getText().toString() == null){
                                    time = 1;
                                } else {
                                    time = HH_CharUtil.Atoi(editText_stop_time.getText().toString());
                                }
                                HH_Logging.i(TAG, "超时间=%d", time);

                                int bst = 1;
                                if (editText_bst.getText() == null || editText_bst.getText().toString() == null){
                                    bst = 1;
                                } else {
                                    bst = HH_CharUtil.Atoi(editText_bst.getText().toString());
                                }
                                bst = bst & 0xFF;

                                long timeBegin = HH_TimeUtil.MadeMillisTimeMS();
                                HH_EnumErrorCode code =  XTCore.BrushPic(systemParams, testMac, listSendData, 10, true, strDeviceIdentity, 1, bst);

                                if (code == HH_EnumErrorCode.FAIL){
                                    HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, "传输失败", 0, 0);
                                } else if (code == HH_EnumErrorCode.BRUSH_FAIL){
                                    HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, "刷图失败", 0, 0);
                                } else {
                                    HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, "其它", 0, 0);
                                }

                                String writeInfo = String.format("\n***********************\nMAC=%s,\n结果=%s,\n耗时=%d毫秒，\n手机型号=%s,\n电量=%d,\nBST=%s,\nPIC=%s,\n抖点类型=%s,\n%s,\n%s,\n%s,\n%s,\n刷图前等待时间=%s毫秒",
                                        testMac,
                                        code.toString(),
                                        HH_TimeUtil.MadeMillisTimeMS() - timeBegin,
                                        HH_SystemUtil.getDeviceModel(),
                                        HH_SystemUtil.GetBatteryPercentage(ctx),
                                        textview_bst_16.getText().toString(),
                                        strSelectPicPath,
                                        textView_dither_type.getText().toString(),
                                        textView_compress_pic.getText().toString(),
                                        textView_border_width.getText().toString(),
                                        textView_border_color.getText().toString(),
                                        textView_filter_type.getText().toString(),
                                        editText_stop_time.getText().toString());
                                //SendToDD(writeInfo);
                            }

                        } catch (Exception e) {
                            HH_Logging.i(TAG, "brush-end fail = %s", e.toString());
                            e.printStackTrace();
                        }
                        bTaskRunning = false;
                    }
                }).start();
                break;
            }
            case R.id.imageview_pic:{
                Intent intent = new Intent(this, HH_Activity_PicFileSelect.class);
                ArrayList<String> listExts = new ArrayList<String>();
                listExts.add("png");
                listExts.add("jpg");
                listExts.add("jpeg");
                listExts.add("bmp");
                intent.putStringArrayListExtra("FIND_FILE_EXT", listExts);
                startActivityForResult(intent, HH_MSG.XT_FILE_SELECT_PIC);
                break;
            }
            case R.id.button_nfc_close:{
                if (bTaskRunning){
                    HH_DialogUtil.tipsDialog(ctx, "任务正在运行");
                    break;
                }
                new Thread(new Runnable() {
                    public void run() {
                        bTaskRunning = true;
                        try {
                            HH_EnumErrorCode code = NFCClose(testMac);
                            HH_Logging.i(TAG, systemParams, "XTCore.NFCClose = %s", code.toString());
                            HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, code.toString(), 0, 0);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        bTaskRunning = false;
                    }
                }).start();
                break;
            }
            case R.id.button_ota:{
                Intent intent = new Intent(this, HH_Activity_PicFileSelect.class);
                ArrayList<String> listExts = new ArrayList<String>();
                listExts.add("bin");
                intent.putStringArrayListExtra("FIND_FILE_EXT", listExts);
                startActivityForResult(intent, HH_MSG.XT_FILE_SELECT_OTA);
                break;
            }
            case R.id.button_phone_info:{

                // 手机型号
                String phoneModel = HH_SystemUtil.getDeviceModel();
                // 电量
                int battery = HH_SystemUtil.GetBatteryPercentage(ctx);

                AddLogInfo(String.format("手机型号：%s", phoneModel));
                AddLogInfo(String.format("电量：%s", battery));

                break;
            }
        }
    }

    private void BrushAllTest() {

        //strSelectPicPath
  /*      // 76 59
        String mac = "38360F017CD9";
        HH_EnumErrorCode code = XTCore.BrushPic(systemParams, mac, ChangePic(HH_PicUtils.GetBitmapFormFile(strSelectPicPath), 59), 10, true, strDeviceIdentity);
        HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, String.format("刷图结果-%s,%s", mac, code.toString()), 0, 0);

        mac = "3538140106F8";
        code = XTCore.BrushPic(systemParams, mac, ChangePic(HH_PicUtils.GetBitmapFormFile(strSelectPicPath), 59), 10, true, strDeviceIdentity);
        HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, String.format("刷图结果-%s,%s", mac, code.toString()), 0, 0);

        mac = "A79260A24E1C";
        code = XTCore.BrushPic(systemParams, mac, ChangePic(HH_PicUtils.GetBitmapFormFile(strSelectPicPath), 59), 10, false, strDeviceIdentity);
        HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, String.format("刷图结果-%s,%s", mac, code.toString()), 0, 0);
*/
    }


    private HH_EnumErrorCode BrushPic(String mac, List<Integer> listData) {
        if (listData == null || listData.size() <= 0)
            return HH_EnumErrorCode.DATA_FAIL;

        int time = 1;
        if (editText_stop_time.getText() == null || editText_stop_time.getText().toString() == null){
            time = 1;
        } else {
            time = HH_CharUtil.Atoi(editText_stop_time.getText().toString());
        }
        HH_Logging.i(TAG, "超时间=%d", time);

        return XTCore.BrushPic(systemParams, mac, listData, 10, true, strDeviceIdentity);
    }

    private HH_EnumErrorCode NFCClose(String mac) {
        return XTCore.NFCClose(systemParams, mac, strDeviceIdentity);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == HH_MSG.XT_FILE_SELECT_PIC){
                if (data != null) {
                    strSelectPicPath = data.getStringExtra("IMPORT_PATH_FILE");
                    LoadLocalPic(strSelectPicPath);
                }
            } else if (requestCode == HH_MSG.XT_FILE_SELECT_OTA){
                if (data != null) {
                    String path = data.getStringExtra("IMPORT_PATH_FILE");
                    OTA(path);
                }
            } else if (requestCode == NFC_BIND_STATE){

                deviceNumber = HH_INI.getInt(systemParams, "DEVICE_NUMBER");

                deviceW = HH_INI.getInt(systemParams, "DEVICE_W");
                deviceH = HH_INI.getInt(systemParams, "DEVICE_H");
                testMac = HH_INI.getString(systemParams, "DEVICE_MAC");
                deviceColorType = HH_INI.getDeviceColor(systemParams, "DEVICE_COLOR");
                textView_w.setText(String.format("%d", deviceW));
                textView_h.setText(String.format("%d", deviceH));
                textView_number.setText(String.format("%d", deviceNumber));
                textView_mac.setText(testMac);
                textView_color.setText(String.format("%d", deviceColorType.ordinal()));

                textView_color_s.setText(HH_INI.getString(systemParams, "DEVICE_COLOR_S"));
                textView_sn.setText(HH_INI.getString(systemParams, "DEVICE_SN"));
                textView_srrc.setText(HH_INI.getString(systemParams, "DEVICE_SRRC"));

                AddLogInfo("绑定成功");
            }
        }
    }

    private void AddLogInfo(String info){
        if (info != null && info.length() > 0){
            mAdapterCurrentTaskLogInfo.addTaskInfo(info);
            mAdapterCurrentTaskLogInfo.notifyDataSetChanged();
            if (mAdapterCurrentTaskLogInfo.getCount() > 0)
                list_log_info.setSelection(mAdapterCurrentTaskLogInfo.getCount() - 1);
        }
    }

    private void OTA(String path) {
        new Thread(new Runnable() {
            public void run() {
                bTaskRunning = true;
                try {
                    HH_EnumErrorCode code = XTCore.OTA(systemParams, testMac, path, 10, strDeviceIdentity);
                    HH_SystemUtil.SendMessage(systemParams, MSG_OTHER_LOG, code.toString(), 0, 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                bTaskRunning = false;
            }
        }).start();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 去掉自动绑定

    }

    //NFC状态监听
    private class NFCStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                NfcManager manager = (NfcManager) ctx.getSystemService(Context.NFC_SERVICE);
                NfcAdapter adapter = manager.getDefaultAdapter();
                if (adapter != null) {
                    if (!adapter.isEnabled()){
                        AddLogInfo("NFC未开启");
                    }else {
                        AddLogInfo("NFC已开启");
                    }
                }
            } catch (Exception e) {
                AddLogInfo("NFC未开启");
            }
        }
    }

    // 监听各种状态
    public class HandlenRecvMessage extends Handler {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case MSG_RE_BIND:{
                    Intent intent = new Intent(ctx, NFCBindActivity.class);
                    startActivityForResult(intent, NFC_BIND_STATE);
                    break;
                }
                case MSG_OTHER_LOG:{
                    AddLogInfo((String)msg.obj);
                    break;
                }
                case XTCore.MSG_PROGRESS:{

                    progressba_brushpic.setMax(msg.arg2);
                    progressba_brushpic.setProgress(msg.arg1 + 1);
                    // 进度值从0开始
                    //AddLogInfo(String.format("数据传输进度%d/%d", msg.arg1, msg.arg2));
                    break;
                }
                case XTCore.MSG_LOG:{
                    HH_EnumErrorCode errorCode = HH_EnumErrorCode.values()[msg.arg2];
                    switch (errorCode) {
                        case DATA_FAIL:
                            AddLogInfo("数据错误");
                            break;
                        case BLE_CONNECT_FAIL:
                            AddLogInfo("连接超时");
                            break;
                        case BLE_CHARACTERISTIC_FAIL:
                            AddLogInfo("特征获取失败");
                            break;
                        case CLEAR_CACHE_FAIL:
                            AddLogInfo("发送清空缓存指令失败");
                            break;
                        case SCAN_FINISH:
                            AddLogInfo("扫描完成");
                            break;
                        case BLE_BEGIN_CONNECT:
                            AddLogInfo("蓝牙开始连接");
                            break;
                        case BLE_DISABLE:
                            AddLogInfo("蓝牙没有打开");
                            break;
                        case BLE_BRUSH_BEGIN:
                            AddLogInfo("刷图开始");
                            break;
                        case BLE_BRUSH_DATA_SEND:
                            AddLogInfo("数据传输中");
                            break;
                        case BLE_NFC_CLOSE_BEGIN:
                            AddLogInfo("NFC断电开始");
                            break;
                        case BLE_OTA_BEGIN:
                            AddLogInfo("OTA开始");
                            break;
                        case SCAN_FAIL:
                            AddLogInfo("扫描失败");
                            break;
                        case SCAN_BEGIN:
                            AddLogInfo("扫描开始");
                            break;
                        case SCAN_INFO: {
                            HH_T_BindDevice tbd = (HH_T_BindDevice) msg.obj;
                            if (tbd != null)
                                AddLogInfo(tbd.getMacRes());
                            break;
                        }
                        case SUCCESS:
                            AddLogInfo("成功");
                            break;
                        case FAIL:
                            AddLogInfo("失败");
                            break;
                        case BLE_CONNECT_SUCCESS:
                            AddLogInfo("蓝牙连接成功");
                            break;
                        case BLE_BRUSH_ING:
                            AddLogInfo("正在刷图");
                            break;
                        case BLE_DISCONNECT:
                            AddLogInfo("断开连接");
                            break;
                        case BLE_IDENTITY_ENCRYPTION_BEGIN:
                            AddLogInfo("身份加密开始");
                            break;
                        case BLE_IDENTITY_ENCRYPTION_FAIL:
                            AddLogInfo("认证失败");
                            break;

                        case TIME_CONSUME_BLE_CONNECT:{
                            AddLogInfo(String.format("连接用时：%d", msg.arg1));
                            break;
                        }
                        case TIME_CONSUME_DATA_SEND:{
                            AddLogInfo(String.format("数据发送用时：%d", msg.arg1));
                            break;
                        }
                        case TIME_CONSUME_BRUSH:{
                            AddLogInfo(String.format("刷图用时：%d", msg.arg1));
                            break;
                        }
                        case OTHER_INFO:{
                            mAdapterCurrentTaskLogInfo.addTaskInfo((String)msg.obj);
                            break;
                        }
                    }
                    break;
                }

            }

        }

    }

    class ScreenStatusReceiver extends BroadcastReceiver {
        String SCREEN_ON = "android.intent.action.SCREEN_ON";
        String SCREEN_OFF = "android.intent.action.SCREEN_OFF";
        @Override
        public void onReceive(Context context, Intent intent) {
            if (SCREEN_ON.equals(intent.getAction())) {

            } else if (SCREEN_OFF.equals(intent.getAction())) {
                AddLogInfo("主动取消");
                new Thread(new Runnable() {

                    public void run() {
                        bTaskRunning = true;
                        try {
                            HH_EnumErrorCode code = NFCClose(testMac);
                            HH_Logging.i(TAG, systemParams, "XTCore.NFCClose = %s", code.toString());
                            XTCore.StopBrushPic();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        bTaskRunning = false;
                    }
                }).start();
            }
        }
    }

    public class BluetoothStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                switch (state) {
                    case BluetoothAdapter.STATE_ON:
                        // 蓝牙已经打开
                        AddLogInfo("蓝牙已经打开");
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        // 蓝牙已经关闭
                        AddLogInfo("蓝牙已经关闭");
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        // 蓝牙正在打开
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        // 蓝牙正在关闭
                        break;
                }
            }
        }
    }




}